package org.omich.loaves;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Random;

public class MainBrain implements IBrain {	
	public  synchronized void newGame(int loavesAmount, int maxWeight) {
		players.clear();
		loaves = new Loaves();
		for (int i = 0; i < loavesAmount; i++) {
			loaves.addLoaf((randomInt(maxWeight - 1) + 1) * 1000);
		}
	}
	
	public synchronized LoavesStatus getStatus() {
		LoavesStatus result = new LoavesStatus();
		ArrayList<Loaf> loavesStore = loaves.getStore();
		
		// add empty players
		for (String player:players) {
			result.getEaters().put(player, null);
			result.getResults().put(player, 0);
		}
		int number = 0;
		// add free loaves and add players progress
		for (Loaf loaf: loavesStore) {
			number++;
			if (loaf.isFree())
				result.getFreeLoaves().put(number, loaf.getWeight());
			if (loaf.isEating())
				result.getEaters().put(loaf.GetEater(), new LoavesStatus.EatingLoaf(number, loaf.getWeight(), loaf.getTail()));
			if (loaf.isEaten())
				result.getResults().put(loaf.GetEater(), result.getResults().get(loaf.GetEater()) + loaf.getWeight());
		}

		return result;
	}
	
	public synchronized void tryToEatLoaf(String playerName, int loafNumber) {
		players.add(playerName);
		loaves.tryToEat(playerName, loafNumber);
	}
	
	private static Random random = new Random();
	private static int randomInt(int n) {
        return Math.abs(random.nextInt()) % n;
    }
	
	private HashSet<String> players = new HashSet<String>();
	private Loaves loaves = new Loaves();
}
